﻿using Services.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Services.DAL
{
    public class UserInfoService
    {
        public static UserInfoResponseEntity Login(UserInfoRequestEntity entity)
        {
            string sql = "SELECT  u.*,t.Token as UserToken FROM UserInfo u,UserToken t WHERE u.ID=t.UID and LoginID = @LoginID  AND LoginPwd = @loginPwd";
            SQLiteParameter[] para = new SQLiteParameter[] {
                new SQLiteParameter ("@LoginID",entity.LoginID),
                new SQLiteParameter ("@LoginPwd",entity.LoginPwd)
            };
            DataTable dt = SQLiteHelper.ExecuteTable(sql, para);
            var user = ModelConvertHelper.ToEntity<UserInfoEntity>(dt);
            return new UserInfoResponseEntity
            {
                Result = user
            };
        }

        public static UserInfoResponseEntity GetUserInfo(string uid)
        {
            string sql = "SELECT  * FROM UserInfo WHERE ID = @ID";
            SQLiteParameter[] para = new SQLiteParameter[] {
                new SQLiteParameter ("@ID",uid)
            };
            DataTable dt = SQLiteHelper.ExecuteTable(sql, para);
            var user = ModelConvertHelper.ToEntity<UserInfoEntity>(dt);
            return new UserInfoResponseEntity
            {
                Result = user
            };
        }

        public static UserInfoResponseEntity Register(UserInfoEntity entity)
        {
            string sql = "insert into UserInfo(LoginID,LoginPwd,RealName,Sex,Birthday,InDate)values(@LoginID,@loginPwd,@RealName,@Sex,@Birthday,@InDate);insert into UserToken(UID,Token,InDate)values(last_insert_rowid(),@Token,@InDate);";
            SQLiteParameter[] para = new SQLiteParameter[] {
                new SQLiteParameter ("@LoginID",entity.LoginID),
                new SQLiteParameter ("@LoginPwd",entity.LoginPwd),
                new SQLiteParameter ("@RealName",entity.RealName),
                new SQLiteParameter ("@Sex",entity.Sex),
                new SQLiteParameter ("@Birthday",entity.Birthday),
                new SQLiteParameter ("@Token",entity.UserToken),
                new SQLiteParameter ("@InDate",DateTime.Now.ToShortDateString())
            };
            return new UserInfoResponseEntity {
                ExeCount= SQLiteHelper.ExecuteNonQuery(sql, para)
            };
        }
    }
}
